package com.easidea.tim.service.purchase;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springside.core.service.EntityService;

import com.easidea.tim.dao.base.FlowNoDao;
import com.easidea.tim.dao.commodity.ProductDao;
import com.easidea.tim.dao.finance.ShouldPayDao;
import com.easidea.tim.dao.finance.ShouldPaySummaryDao;
import com.easidea.tim.dao.purchase.PurchaseOrderDao;
import com.easidea.tim.dao.purchase.PurchaseOrderItemDao;
import com.easidea.tim.dao.supply.SupDao;
import com.easidea.tim.entity.commodity.Product;
import com.easidea.tim.entity.finance.ShouldPay;
import com.easidea.tim.entity.finance.ShouldPaySummary;
import com.easidea.tim.entity.purchase.PurchaseOrder;
import com.easidea.tim.entity.purchase.PurchaseOrderItem;
import com.easidea.tim.entity.supply.Sup;
import com.easidea.tim.util.DateUtil;
import com.easidea.tim.util.Page;
import com.easidea.tim.util.TimConstant.FlowNoType;

public class PurchaseOrderService extends EntityService<PurchaseOrder, PurchaseOrderDao> {
	private PurchaseOrderDao purchaseOrderDao;

	private PurchaseOrderItemDao purchaseOrderItemDao;
	
	private SupDao supDao;
	
	private ProductDao productDao;
	
	private FlowNoDao flowNoDao;
	
	private ShouldPaySummaryDao shouldPaySummaryDao;
	
	private ShouldPayDao shouldPayDao;
	
	public void setShouldPayDao(ShouldPayDao shouldPayDao) {
		this.shouldPayDao = shouldPayDao;
	}
	public void setShouldPaySummaryDao(ShouldPaySummaryDao shouldPaySummaryDao) {
		this.shouldPaySummaryDao = shouldPaySummaryDao;
	}
	/**
	 * 分页获取采购合同列表
	 * @param page
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Page getPurchaseOrderListByCondition(String purchaseOrderNum,String supplierName,Date startTime,Date endTime,Page page) {
		Criteria ca = createPurchaseOrderListByConditionCriteria(purchaseOrderNum,supplierName,startTime,endTime);
		ca.setProjection(Projections.count("id"));
		Integer totalNum = (Integer) ca.uniqueResult();
		Criteria ca1 = createPurchaseOrderListByConditionCriteria(purchaseOrderNum,supplierName,startTime,endTime);
		int startIndex = Page.getStartOfPage(page.getCurrentPageNo(), page.getPageSize());
		ca1.setFirstResult(startIndex);
		ca1.setMaxResults(page.getPageSize());
		List<PurchaseOrder> ls = (List<PurchaseOrder>) ca1.list();
//		List<PurchaseOrderDTO> dtos = new ArrayList<PurchaseOrderDTO>();
//		for (PurchaseOrder cs : ls) {
//			dtos.add(purchaseOrder2Dto(cs));
//		}
		Page resultPage = new Page(startIndex, totalNum, page.getPageSize(), ls);
		resultPage.setCurrentPageNo(page.getCurrentPageNo());

		return resultPage;

	}
	private Criteria createPurchaseOrderListByConditionCriteria(String purchaseOrderNum,String supplierName,Date startTime,Date endTime){
		Criteria ca = createUnDeletedCriteria();
		if(purchaseOrderNum != null && !purchaseOrderNum.equals("")) {
			ca.add(Restrictions.ilike("purchaseOrderNum", purchaseOrderNum, MatchMode.START));
		}
		if(supplierName != null && !supplierName.equals("")) {
			ca.add(Restrictions.ilike("supplier.supplierName", supplierName, MatchMode.START));
		}
		if(startTime != null && !startTime.equals("") && endTime != null && !endTime.equals("") ) {
			ca.add(Restrictions.between("createTime", DateUtil.getStartTime(startTime), DateUtil.getEndTime(endTime)));
		}
				
		return ca;
	}

	/**
	 * 新增或修改时获取初始化数据列表（供应商列表）
	 * @return
	 */
	public List<Sup> filteSupByName(String name) {
		return supDao.filteSupByName(name);
	}

	public List<Product> filteProductByName(String name){
		return productDao.filteProductByName(name);
	}
	/**
	 * 新增或修改保存采购合同
	 * @param dto
	 * @param items
	 * @return
	 */
	public boolean saveOrUpdate(PurchaseOrder order, List<PurchaseOrderItem> items) {

		if (order.getId() == -1) {
			String flowNo = flowNoDao.genNextFlowNo(FlowNoType.PURCHASE_ORDER);
			order.setFlowNo(flowNo);
			this.purchaseOrderDao.getHibernateTemplate().save(order);
		} else {

			this.purchaseOrderDao.getHibernateTemplate().update(order);
			this.purchaseOrderItemDao.deleteItemsByOrderId(order.getId());
		}		
		for (PurchaseOrderItem item : items) {
			 Product  product = this.productDao.isExistSame(item.getProductName(), item.getProductColorCode());
			 if(product == null) {//不存在同产品信息则新增产品信息
				 product = new Product();
				 product.setCreator(item.getCreator());
				 product.setModifier(item.getModifier());
				 product.setCreateTime(item.getCreateTime());
				 product.setModifyTime(item.getModifyTime());
				 product.setName(item.getProductName());
				 product.setBasicPrice(item.getProductPurchasePrice().floatValue());
				 product.setColorCode(item.getProductColorCode());
				 this.productDao.save(product);
			 }
			 item.setPurchaseOrder(order);
			this.purchaseOrderItemDao.savePurchaseOrderItem(item);
		}
		return true;
	}

	
	public PurchaseOrder getPurchaseOrderById(long id) {
		return get(id);
	}
	/**
	 * 删除采购合同及明细
	 * @param id
	 */
	public String deletePurchaseOrder(long id){	
	  try {	
		List<PurchaseOrderItem> items = this.purchaseOrderItemDao.getItemsByOrderId(id);
		for(PurchaseOrderItem item : items) {
			item.setDeleted((short)1);
			item.setModifyTime(new Date());
			this.purchaseOrderItemDao.getHibernateTemplate().update(item);
		}
		PurchaseOrder order = this.get(id);
		order.setDeleted((short)1);
		order.setModifyTime(new Date());
		this.purchaseOrderDao.getHibernateTemplate().update(order);
		ShouldPaySummary paySummary = shouldPaySummaryDao.getShouldPaySummaryBySupId(order.getSupplier().getId());
		if (paySummary != null) {
			paySummary.setDeleted((short)1);
			shouldPaySummaryDao.getHibernateTemplate().update(paySummary);
		}
		ShouldPay pay = this.shouldPayDao.getShouldPayByOrderId(order.getId());
		if (pay != null) {
			pay.setDeleted((short)1);
			shouldPayDao.getHibernateTemplate().update(pay);
		}
	  }catch(DataAccessException de) {
		 return de.getMessage();
	  }
	  return "success";
	}
	public boolean closePurchaseOrder(long id, String closeMan) {
		PurchaseOrder order = this.get(id);
		order.setCloseDate(new Date());
		order.setStatus(true);
		order.setCloseMan(closeMan);
		order.setModifyTime(new Date());
		this.purchaseOrderDao.getHibernateTemplate().update(order);
		return true;
	}
	/**
	 * 合同统计
	 * @param startDate
	 * @param endDate
	 * @param statType(按产品或供应商)
	 * @return
	 */
	public List<Object[]> statPurchaseOrder(Date startDate, Date endDate,String statType) {
		if(statType.equals("product")) {
			return this.purchaseOrderDao.statPurchaseOrderByProductTest(startDate, endDate);
		} else {
			return this.purchaseOrderDao.statPurchaseOrderBySupplierTest(startDate, endDate);
		}

	}
	
	
	
	/**
	 * 根据采购合同编号，提取采购所有有效的采购订单中对应的产品列表
	 * 
	 * @param billNum
	 * @return
	 */
	public List<Object[]> getPurchaseOrderProductList(String billNum){
		if(StringUtils.isNotBlank(billNum)){
			Criteria cte = purchaseOrderItemDao.createUnDeletedCriteria();
			cte.createAlias("purchaseOrder", "purchaseOrder");
			cte.add(Restrictions.eq("purchaseOrder.purchaseOrderNum", billNum));
			List<PurchaseOrderItem> poItemList = cte.list();
			
			if(poItemList != null && poItemList.size()>0){
				List<Object[]> rtnList = new ArrayList<Object[]>();
				for(PurchaseOrderItem poItem : poItemList){
					Object[] tmpData = new Object[]{poItem.getProductName(),poItem.getProductColorCode()};
					rtnList.add(tmpData);
				}
				return rtnList;
			}
		}
		return null;
	}
	
	public List<Object[]> getproductDetailSimple(Date startDate, Date endDate,String name) {
		return this.purchaseOrderDao.getproductDetailSimple(startDate, endDate,name);
	}
	
	public List<Object[]> getsuppliyDetailSimple(Date startDate, Date endDate,String id) {
		return this.purchaseOrderDao.getsuppliyDetailSimple(startDate, endDate,id);
	}
	
	
	
	/**
	 * 根据合同编号提取采购合同
	 * 
	 * @param pon
	 * @return
	 */
	public PurchaseOrder getPOByPON(String pon){
		return purchaseOrderDao.getPOByPon(pon);
	}
	
	
	public List<Object[]> statPurchaseOrderByMonth(int year, int month){
		return purchaseOrderDao.statPurchaseOrderByMonth(year, month);
	}
	public boolean isExistSupplier(String supplierName) {
		Sup sp = this.supDao.findUniqueBy("name", supplierName);
		if(sp != null) {
			return true;
		}
		return false;
	}
	@Override
	public PurchaseOrderDao getEntityDao() {
		return purchaseOrderDao;
	}

	public PurchaseOrderDao getPurchaseOrderDao() {
		return purchaseOrderDao;
	}

	public void setPurchaseOrderDao(PurchaseOrderDao purchaseOrderDao) {
		this.purchaseOrderDao = purchaseOrderDao;
	}

	public void setPurchaseOrderItemDao(PurchaseOrderItemDao purchaseOrderItemDao) {
		this.purchaseOrderItemDao = purchaseOrderItemDao;
	}


	public void setSupDao(SupDao supDao) {
		this.supDao = supDao;
	}
	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}
	public void setFlowNoDao(FlowNoDao flowNoDao) {
		this.flowNoDao = flowNoDao;
	}

}
